package io.github.lianghengyuan.international.utils;

import io.github.lianghengyuan.international.domain.I18n;
import io.github.lianghengyuan.international.service.II18nService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author JiangSuihua
 * @date 2024/02/21 13:32
 **/
@Component
public class LanguageUtils {

    private static final Logger log = LoggerFactory.getLogger(LanguageUtils.class);

    @Autowired
    private II18nService II18NService;


//    @Cacheable(cacheNames ="international", cacheManager = "redisCacheManager", key = "#key+'.'+#internationalLanguage",unless = "#result == #key")
    @Cacheable(cacheNames ="international", key = "#key+'.'+#internationalLanguage",unless = "#result == #key")
    public String getValueByKeyDB(String key,String internationalLanguage) {
        I18n i18n = new I18n();
        i18n.setWkey(key);
        List<I18n> i18ns = II18NService.selectI18nList(i18n);
        if (CollectionUtils.isEmpty(i18ns)) {
            // 数据库中查询不到，返回key值
            log.error("i18n中找不到key为{}的项",key);
            return key;
        }
        I18n i18nt = i18ns.get(0);
        String value = getValue(i18nt, internationalLanguage);
        if (StringUtils.isEmpty(value) || "None".equals(value)) {
            return key;
        }
        return  value;
    }

    private static String getValue(I18n i18n,String internationalLanguage) {
        if(internationalLanguage.contains("zh")){
            return i18n.getZh();
        }
        if(internationalLanguage.contains("en")){
            return i18n.getEn();
        }
        if(internationalLanguage.contains("ru")){
            return i18n.getRu();
        }
        if(internationalLanguage.contains("sp")){
            return i18n.getSp();
        }
        if(internationalLanguage.contains("fr")){
            return i18n.getFr();
        }
        return null;
    }


}
